package com.epalmpay.service.withdraw.impl;

import com.epalmpay.exception.ApplicationException;
import com.epalmpay.dto.agentmanage.TradeWithdrawListInDTO;
import com.epalmpay.dto.agentmanage.TradeWithdrawOutDTO;
import com.epalmpay.entity.*;
import com.epalmpay.enumdef.BizEnum;
import com.epalmpay.enumdef.CommonEnum;
import com.epalmpay.mapper.*;
import com.epalmpay.payplat.*;
import com.epalmpay.payplat.result.*;
import com.epalmpay.service.weixin.IWalletService;
import com.epalmpay.service.weixin.IWxApiWalletService;
import com.epalmpay.service.withdraw.ITradeWithdrawService;
import com.epalmpay.util.Const;
import com.epalmpay.util.Tools;
import com.epalmpay.util.payplat.DateUtils;
import com.epalmpay.util.payplat.UtilFun;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * Created by Administrator on 2017/6/6.
 */
@Service("tradeWithdrawService")
public class TradeWithdrawServiceImpl implements ITradeWithdrawService{

    @Resource
    TradeWithdrawMapper tradeWithdrawMapper;

    @Resource
    private AgentMapper agentMapper;

    @Resource
    private ShopMapper shopMapper;

    @Resource
    private GroupMapper groupMapper;

    @Resource
    private ShopGroupRelationMapper shopGroupRelationMapper;

    @Resource
	private TradeOfflineMapper tradeOfflineMapper;

    @Resource
    private IWxApiWalletService wxApiWalletServiceService;
    
    @Resource
    private IWalletService walletService;

    @Override
    public List<TradeWithdrawOutDTO> getTradeWithdrawList(TradeWithdraw tradeWithdraw, Page page) throws Exception {
        Map<String,Object> param=new HashMap<String,Object>();
        param.put("groupId", tradeWithdraw.getGroupId());
        param.put("status", tradeWithdraw.getStatus());
        param.put("startDate", tradeWithdraw.getStartDate());
        param.put("endDate", tradeWithdraw.getEndDate());
        param.put("name", tradeWithdraw.getName());

        List<TradeWithdrawOutDTO> result = new ArrayList<TradeWithdrawOutDTO>();

        int sumCount = tradeWithdrawMapper.selectTradeWithdrawListCount(param);
        page.setTotalResult(sumCount);
        if(sumCount<=0)
            return null;

        param.put("limit", page.getShowCount());
        param.put("start", page.getShowCount()*(page.getCurrentPage()-1));

        List<Map<String,Object>> tradeWithdrawOutDTOList = tradeWithdrawMapper.selectTradeWithdrawList(param);

        for (Map<String, Object> tempObject : tradeWithdrawOutDTOList) {
            TradeWithdrawOutDTO tradeWithdrawOutDTO = new TradeWithdrawOutDTO();
            tradeWithdrawOutDTO.setId((Long)tempObject.get("id"));
            tradeWithdrawOutDTO.setGmtCreate((Date)tempObject.get("gmt_create"));

            tradeWithdrawOutDTO.setSettleCode((String) tempObject.get("settle_code"));
            tradeWithdrawOutDTO.setWalletOrderId((String) tempObject.get("wallet_order_id"));
            tradeWithdrawOutDTO.setGmtModified((Date)tempObject.get("gmt_modified"));
            tradeWithdrawOutDTO.setAgentId((Long)tempObject.get("agent_id"));
            tradeWithdrawOutDTO.setShopId((Long)tempObject.get("shop_id"));
            tradeWithdrawOutDTO.setGroupId((Long)tempObject.get("group_id"));
            tradeWithdrawOutDTO.setStatus((Integer) tempObject.get("status"));
            tradeWithdrawOutDTO.setApplyAmount((Integer) tempObject.get("apply_amount"));
            tradeWithdrawOutDTO.setAfterApplyAmount((Integer) tempObject.get("after_apply_amount"));

            tradeWithdrawOutDTO.setAuditPackNo((String) tempObject.get("audit_pack_no"));

            if (!Tools.isEmpty((String) tempObject.get("agent_name"))){
                tradeWithdrawOutDTO.setName((String) tempObject.get("agent_name"));
            }else{
                tradeWithdrawOutDTO.setName((String) tempObject.get("shop_name"));
            }
            result.add(tradeWithdrawOutDTO);
        }

        return result;
    }


    @Override
    public TradeWithdraw GetTradeWithdrawById(Long id) throws Exception {

        Map<String,Object> tempObject=tradeWithdrawMapper.selectTradeWithByIdLeftJoin(id);
        TradeWithdraw tradeWithdraw = new TradeWithdraw();
        tradeWithdraw.setId((Long)tempObject.get("id"));
        tradeWithdraw.setGmtCreate((Date)tempObject.get("gmt_create"));

        tradeWithdraw.setSettleCode((String) tempObject.get("settle_code"));
        tradeWithdraw.setWalletOrderId((String) tempObject.get("wallet_order_id"));
        tradeWithdraw.setGmtModified((Date)tempObject.get("gmt_modified"));
        tradeWithdraw.setAgentId((Long)tempObject.get("agent_id"));
        tradeWithdraw.setShopId((Long)tempObject.get("shop_id"));
        tradeWithdraw.setGroupId((Long)tempObject.get("group_id"));
        tradeWithdraw.setStatus((Integer) tempObject.get("status"));
        tradeWithdraw.setApplyAmount((Integer) tempObject.get("apply_amount"));
        tradeWithdraw.setAfterApplyAmount((Integer) tempObject.get("after_apply_amount"));
        if (!Tools.isEmpty((String) tempObject.get("agent_name"))){
            tradeWithdraw.setName((String) tempObject.get("agent_name"));
        }else{
            tradeWithdraw.setName((String) tempObject.get("shop_name"));
        }

        tradeWithdraw.setAuditor((Long)tempObject.get("auditor"));
        tradeWithdraw.setAuditTime((Date)tempObject.get("audit_time"));
        tradeWithdraw.setAuditMemo((String)tempObject.get("audit_demo"));
        tradeWithdraw.setEditAmount((Integer) tempObject.get("edit_amount"));
        tradeWithdraw.setEditAmountUserid((Long) tempObject.get("edit_amount_userid"));
        tradeWithdraw.setEditAmountTime((Date) tempObject.get("edit_amount_time"));
        tradeWithdraw.setSettleContent((String)tempObject.get("settle_content"));
        tradeWithdraw.setAuditorName((String)tempObject.get("auditor_name"));
        tradeWithdraw.setEditAmountName((String)tempObject.get("edit_amount_name"));
        tradeWithdraw.setFee((Integer) tempObject.get("fee"));
        tradeWithdraw.setAuditPackNo((String) tempObject.get("audit_pack_no"));
        return tradeWithdraw;
    }


    @Override
    public int UpdateTradeWithdrawById(TradeWithdraw tradeWithdraw,HttpServletRequest request) throws Exception {

        TradeWithdraw tempObject=tradeWithdrawMapper.selectByPrimaryKey(tradeWithdraw.getId());

        if (!Tools.isEmpty(tradeWithdraw.getAgentId()+"")){
            if (tradeWithdraw.getStatus()==BizEnum.WithdrawStatus.ConfirmTheFight.getType()){
                throw new ApplicationException("fail","代理商不存在打款操作");
            }
            Agent agent=agentMapper.selectByPrimaryKey(tradeWithdraw.getAgentId());
            if(agent==null){
                throw new ApplicationException("fail","代理商不存在");
            }
            Group group = groupMapper.selectByPrimaryKey(agent.getGroupId());
            String groupId = group.getPayGroupCode();
            String sysTraceNum = UtilFun.createRandomNum(10);
            String orgOrderNum =tempObject.getWalletOrderId()+"";
            String userId=agent.getPacketNum();
            String orgTranDateTime = DateUtils.getDateTimeString("yyyyMMddHHmmss");
            String transAmt=tempObject.getApplyAmount()+"";
            String transCode;
            if (tradeWithdraw.getStatus()==BizEnum.WithdrawStatus.Doing.getType()){
                transCode="1";
            }else if (tradeWithdraw.getStatus()==BizEnum.WithdrawStatus.AuditRefuse.getType()){
                transCode="0";
            }else{
                transCode="0";
            }
            WarrantDrawFinish pw= WarrantDrawFinish.initialize(orgOrderNum,groupId,transAmt,orgTranDateTime,"2",transCode);
            PayResult payResult=IPayAPI.WarrantDrawFinish(pw); 
            
            int status=1;
            if(!PayResult.SUCCESS.equals(payResult.getRespCode())){
               
                throw new ApplicationException(payResult.getRespCode(),payResult.getMsgTxt());
            }else{
            	   TradeWithdraw  tradeWithdraw1=tradeWithdrawMapper.selectByPrimaryKey(tradeWithdraw.getId());
               
                   if (tradeWithdraw1.getStatus()!=BizEnum.WithdrawStatus.SettleSuccess.getType()){
                       status=tradeWithdrawMapper.updateByPrimaryKeySelective(tradeWithdraw);
                   }
            }
            return status;
        }

        if (!Tools.isEmpty(tradeWithdraw.getShopId()+"")){
            Shop shop=shopMapper.selectShopInfo(tradeWithdraw.getShopId(),tradeWithdraw.getGroupId());
            if(shop==null){
                throw new ApplicationException("fail","门店不存在");
            }
            String groupId=shop.getGroup().getPayGroupCode();
            String merchantId=shop.getShopGroupRelation().getPayMerchantCode();
//            Shop shop=shopMapper.selectByPrimaryKey(tradeWithdraw.getShopId());

          
            Group group = groupMapper.selectByPrimaryKey(tradeWithdraw.getGroupId());
//            String groupId = group.getPayGroupCode();
            String sysTraceNum = UtilFun.createRandomNum(10);
            String orgOrderNum =tempObject.getWalletOrderId()+"";
            String auditPackNo =tempObject.getAuditPackNo()+"";
            String userId=shop.getMerchantId()+"";
            String orgTranDateTime = DateUtils.getDateTimeString("yyyyMMddHHmmss");
            String transAmt=tempObject.getApplyAmount()+"";
            String transCode;
            String ipAddress=Tools.getIpAddr(request);
            if (tradeWithdraw.getStatus()==BizEnum.WithdrawStatus.Doing.getType()){
                transCode="1";
            }else if (tradeWithdraw.getStatus()==BizEnum.WithdrawStatus.AuditRefuse.getType()){
                transCode="0";
            }else{
                transCode="0";
            }
            if (tradeWithdraw.getStatus()!=BizEnum.WithdrawStatus.ConfirmTheFight.getType()) {
                MerchantWithsApprove merchantWithsApprove = MerchantWithsApprove.initialize(groupId, orgOrderNum, transCode,  "可信度低", merchantId,transAmt,ipAddress);

                PayApproveResult payResult = IPayAPI.merchantWithsApprove(merchantWithsApprove);
                if (!PayResult.SUCCESS.equals(payResult.getRespCode())) {
                    throw new ApplicationException(payResult.getRespCode(), payResult.getMsgTxt());
                }
                tradeWithdraw.setAuditPackNo(payResult.getAuditPackNo());

                //        更新表数据
                TradeWithdraw  tradeWithdraw1=tradeWithdrawMapper.selectByPrimaryKey(tradeWithdraw.getId());
                int status=1;
                if (tradeWithdraw1.getStatus()!=BizEnum.WithdrawStatus.SettleSuccess.getType()){
                    status=tradeWithdrawMapper.updateByPrimaryKeySelective(tradeWithdraw);
                }

                return status;
            }else{
                MerchantWithsPay merchantWithsPay = MerchantWithsPay.initialize(groupId,orgOrderNum,auditPackNo,merchantId);

                PayWithdrawalResult payResult = IPayAPI.MerchantWithsPay(merchantWithsPay);
                if (!PayResult.SUCCESS.equals(payResult.getRespCode())) {
                    throw new ApplicationException(payResult.getRespCode(), payResult.getMsgTxt());
                }else{
                    tradeWithdraw.setStatus(BizEnum.WithdrawStatus.ConfirmTheFight.getType());
                    TradeWithdraw  tradeWithdraw1=tradeWithdrawMapper.selectByPrimaryKey(tradeWithdraw.getId());
                    int status=1;
                    if (tradeWithdraw1.getStatus()!=BizEnum.WithdrawStatus.SettleSuccess.getType()){
                        status=tradeWithdrawMapper.updateByPrimaryKeySelective(tradeWithdraw);
                    }

                    return status;
                }
            }
        }
        return 1;


    }


    @Override
    public int BatchUpdateTradeWithdrawById(TradeWithdraw tradeWithdraw,HttpServletRequest request) throws Exception {
        Map<String,Object> param=new HashMap<String,Object>();
        param.put("groupId", tradeWithdraw.getGroupId());
        param.put("startDate", tradeWithdraw.getStartDate());
        param.put("endDate", tradeWithdraw.getEndDate());
        param.put("agentId", tradeWithdraw.getAgentId());
        param.put("shopId", tradeWithdraw.getShopId());

        String tempStr=StringUtils.strip(tradeWithdraw.getIdList().toString(),"[]");
        String [] stringArr= tempStr.split(",");


        for (String id: stringArr) {

            TradeWithdraw tempObject=tradeWithdrawMapper.selectByPrimaryKey(Long.parseLong(id.trim()));

            if (!Tools.isEmpty(tempObject.getAgentId()+"")) {
                if (tradeWithdraw.getStatus()==BizEnum.WithdrawStatus.ConfirmTheFight.getType()){
                    continue;
                }
                if (tradeWithdraw.getStatus()==BizEnum.WithdrawStatus.SettleSuccess.getType()){
                    continue;
                }
                if (tradeWithdraw.getStatus()==BizEnum.WithdrawStatus.SettleFail.getType()){
                    continue;
                }


                Agent agent=agentMapper.selectByPrimaryKey(tempObject.getAgentId());
                if(agent==null){
                    throw new ApplicationException("fail","代理商不存在");
                }
                Group group = groupMapper.selectByPrimaryKey(agent.getGroupId());
                String groupId = group.getPayGroupCode();
                String orgOrderNum =tempObject.getWalletOrderId()+"";
                String orgTranDateTime = DateUtils.getDateTimeString("yyyyMMddHHmmss");
                String transAmt=tempObject.getApplyAmount()+"";
                String transCode;
                if (tradeWithdraw.getStatus()==BizEnum.WithdrawStatus.Doing.getType()){
                    transCode="1";
                }else if (tradeWithdraw.getStatus()==BizEnum.WithdrawStatus.AuditRefuse.getType()){
                    transCode="0";
                }else{
                    transCode="0";
                }

                WarrantDrawFinish pw= WarrantDrawFinish.initialize(orgOrderNum,groupId,transAmt,orgTranDateTime,"2",transCode);

                PayResult payResult=IPayAPI.WarrantDrawFinish(pw);
                if (!PayResult.SUCCESS.equals(payResult.getRespCode())) {
                    tradeWithdraw.setStatus(BizEnum.WithdrawStatus.SettleFail.getType());
                     wxApiWalletServiceService.updateWxWithDrawNotify(orgOrderNum,"",null);
                }


//        更新表数据
                TradeWithdraw  tradeWithdraw1=tradeWithdrawMapper.selectByPrimaryKey(tempObject.getId());
                if (tradeWithdraw1.getStatus()!=BizEnum.WithdrawStatus.SettleSuccess.getType()){
                    tradeWithdrawMapper.updateByPrimaryKeySelective(tradeWithdraw);
                }
            }

            if (!Tools.isEmpty(tempObject.getShopId()+"")) {
                if (tradeWithdraw.getStatus()==BizEnum.WithdrawStatus.SettleSuccess.getType()){
                    continue;
                }
                if (tradeWithdraw.getStatus()==BizEnum.WithdrawStatus.SettleFail.getType()){
                    continue;
                }

                Shop shop=shopMapper.selectShopInfo(tempObject.getShopId(),tempObject.getGroupId());
                
                if(shop==null){
                    throw new ApplicationException("fail","门店不存在");
                }
                
                String groupId=shop.getGroup().getPayGroupCode();
                String merchantId=shop.getShopGroupRelation().getPayMerchantCode();

                
                String orgOrderNum =tempObject.getWalletOrderId()+"";
                String auditPackNo =tempObject.getAuditPackNo()+"";
                String transAmt=tempObject.getApplyAmount()+"";
                String transCode;
                String ipAddress=Tools.getIpAddr(request);
                if (tradeWithdraw.getStatus()==BizEnum.WithdrawStatus.Doing.getType()){
                    transCode="1";
                }else if (tradeWithdraw.getStatus()==BizEnum.WithdrawStatus.AuditRefuse.getType()){
                    transCode="0";
                }else{
                    transCode="0";
                }
                if (tradeWithdraw.getStatus()!=BizEnum.WithdrawStatus.ConfirmTheFight.getType()) {
                    MerchantWithsApprove merchantWithsApprove = MerchantWithsApprove.initialize(groupId, orgOrderNum, transCode,  "可信度低", merchantId,transAmt,ipAddress);

                    PayApproveResult payResult = IPayAPI.merchantWithsApprove(merchantWithsApprove);
                    if (!PayResult.SUCCESS.equals(payResult.getRespCode())) {
                        continue;
                    }
                    tradeWithdraw.setAuditPackNo(payResult.getAuditPackNo());

                    //        更新表数据
                    TradeWithdraw  tradeWithdraw1=tradeWithdrawMapper.selectByPrimaryKey(tempObject.getId());
                    if (tradeWithdraw1.getStatus()!=BizEnum.WithdrawStatus.SettleSuccess.getType()){
                       tradeWithdrawMapper.updateByPrimaryKeySelective(tradeWithdraw);
                    }

                }else {
                    MerchantWithsPay merchantWithsPay = MerchantWithsPay.initialize(groupId, orgOrderNum, auditPackNo, merchantId);

                    PayWithdrawalResult payResult = IPayAPI.MerchantWithsPay(merchantWithsPay);
                    if (!PayResult.SUCCESS.equals(payResult.getRespCode())) {
                        throw new ApplicationException(payResult.getRespCode(), payResult.getMsgTxt());
                    } else {
                        tradeWithdraw.setStatus(BizEnum.WithdrawStatus.ConfirmTheFight.getType());
                        TradeWithdraw  tradeWithdraw1=tradeWithdrawMapper.selectByPrimaryKey(tempObject.getId());
                        if (tradeWithdraw1.getStatus()!=BizEnum.WithdrawStatus.SettleSuccess.getType()){
                            tradeWithdrawMapper.updateByPrimaryKeySelective(tradeWithdraw);
                        }
                    }
                }
            }

        }
        return 1;
    }

    @Override
    public int UpdateTradeWithdrawByList(TradeWithdrawListInDTO tradeWithdrawListInDTO) throws Exception {
        int result=tradeWithdrawMapper.UpdateTradeWithdrawByList(tradeWithdrawListInDTO.getIdList(),tradeWithdrawListInDTO.getStatus());
        return result;
    }


    @Override
    public List<TradeWithdrawOutDTO> GetWithdrawListByAgentIdOrShopId(TradeWithdraw tradeWithdraw, Page page) throws Exception {
        Map<String,Object> param=new HashMap<String,Object>();
        param.put("groupId", tradeWithdraw.getGroupId());
        param.put("status", tradeWithdraw.getStatus());
        param.put("startDate", tradeWithdraw.getStartDate());
        param.put("endDate", tradeWithdraw.getEndDate());
        param.put("agentId", tradeWithdraw.getAgentId());
        param.put("shopId", tradeWithdraw.getShopId());

        List<TradeWithdrawOutDTO> result = new ArrayList<TradeWithdrawOutDTO>();

        int sumCount = tradeWithdrawMapper.selectTradeWithdrawListCount(param);
        page.setTotalResult(sumCount);
        if(sumCount<=0)
            return null;

//        param.put("limit", page.getShowCount());
//        param.put("start", page.getShowCount()*(page.getCurrentPage()-1));

        List<Map<String,Object>> tradeWithdrawOutDTOList = tradeWithdrawMapper.selectTradeWithdrawListByAgentIdOrShopId(param);
        for (Map<String, Object> tempObject : tradeWithdrawOutDTOList) {
            TradeWithdrawOutDTO tradeWithdrawOutDTO = new TradeWithdrawOutDTO();
            tradeWithdrawOutDTO.setId((Long)tempObject.get("id"));
            tradeWithdrawOutDTO.setGmtCreate((Date)tempObject.get("gmt_create"));

            tradeWithdrawOutDTO.setSettleCode((String) tempObject.get("settle_code"));
            tradeWithdrawOutDTO.setWalletOrderId((String) tempObject.get("wallet_order_id"));
            tradeWithdrawOutDTO.setGmtModified((Date)tempObject.get("gmt_modified"));
            tradeWithdrawOutDTO.setAgentId((Long)tempObject.get("agent_id"));
            tradeWithdrawOutDTO.setShopId((Long)tempObject.get("shop_id"));
            tradeWithdrawOutDTO.setGroupId((Long)tempObject.get("group_id"));
            tradeWithdrawOutDTO.setStatus((Integer) tempObject.get("status"));
            tradeWithdrawOutDTO.setApplyAmount((Integer) tempObject.get("apply_amount"));
            tradeWithdrawOutDTO.setAfterApplyAmount((Integer) tempObject.get("after_apply_amount"));
            if (!Tools.isEmpty((String) tempObject.get("agent_name"))){
                tradeWithdrawOutDTO.setName((String) tempObject.get("agent_name"));
            }else{
                tradeWithdrawOutDTO.setName((String) tempObject.get("shop_name"));
            }
            result.add(tradeWithdrawOutDTO);
        }

        return result;
    }


    @Override
    @Transactional
    public int ApplyWithdrawById(TradeWithdraw tradeWithdraw) throws ApplicationException {
        if (!Tools.isEmpty(tradeWithdraw.getAgentId()+"")){
//            Map<String,Object> param=new HashMap<String,Object>();
//            param.put("groupId", tradeWithdraw.getGroupId());
//            param.put("startDate", tradeWithdraw.getStartDate());
//            param.put("endDate", tradeWithdraw.getEndDate());
//            param.put("agentId", tradeWithdraw.getAgentId());
//            param.put("shopId", tradeWithdraw.getShopId());
//            List<Map<String,Object>> tradeWithdrawOutDTOList=tradeWithdrawMapper.selectTradeWithdrawListSpecial(param);
//            if (tradeWithdrawOutDTOList.size()>0){
//                throw new ApplicationException("fail","之前的申请提现还没有完毕");
//            }
            Agent agent=agentMapper.selectByPrimaryKey(tradeWithdraw.getAgentId());
            if(agent==null){
                throw new ApplicationException("fail","代理商不存在");
            }
            Group group = groupMapper.selectByPrimaryKey(agent.getGroupId());
            

            String groupId = group.getPayGroupCode();
            String userId=agent.getPacketNum();
            String orgOrderNum = Const.PLATFORM_WITHDEAW+UtilFun.createOrderNum();
            
            PayResult payResult=walletService.updateWarrantWithdrawal(userId, groupId, agent.getUserId(), tradeWithdraw.getApplyAmount(), orgOrderNum, tradeWithdraw.getPayPwd(), 0);
	          if(!PayResult.SUCCESS.equals(payResult.getRespCode())){
	              throw new ApplicationException(payResult.getRespCode(),payResult.getMsgTxt());
	          }
            
            //插入的数据修改填充
            tradeWithdraw.setStatus(BizEnum.WithdrawStatus.WaitingForSettle.getType());
            if (payResult.getOrderId()!=null){
                tradeWithdraw.setWalletOrderId(payResult.getOrderId());
            }

            tradeWithdraw.setTraceNo(orgOrderNum);
            tradeWithdraw.setFee(0);
            tradeWithdraw.setGmtCreate(new Date());
            tradeWithdraw.setGmtModified(new Date());
            tradeWithdraw.setSettleCode(userId);
            int status=tradeWithdrawMapper.insert(tradeWithdraw);
            TradeOffline tradeOffline=addTradeOffline(orgOrderNum, tradeWithdraw.getGroupId(), tradeWithdraw.getApplyAmount(), agent.getId(), agent.getMerchantName(),2);
            tradeOfflineMapper.insertSelective(tradeOffline);
            return status;
        }
        if (!Tools.isEmpty(tradeWithdraw.getShopId()+"")){
            Shop shop=shopMapper.selectShopInfo(tradeWithdraw.getShopId(),tradeWithdraw.getGroupId());
            if(shop==null){
                throw new ApplicationException("fail","门店不存在");
            }
            String groupId=shop.getGroup().getPayGroupCode();
            String merchantId=shop.getShopGroupRelation().getPayMerchantCode();
            String orgOrderNum =Const.PLATFORM_WITHDEAW+UtilFun.createOrderNum();
            
//            MerchantWithsDraw merchantWithsDraw=MerchantWithsDraw.initialize(groupId,orgOrderNum,tradeWithdraw.getApplyAmount()+"",merchantId);
//            PayTransferResult payResult=IPayAPI.merchantWithsDraw(merchantWithsDraw);
//            if(!PayResult.SUCCESS.equals(payResult.getRespCode())){
//                throw new ApplicationException(payResult.getRespCode(),payResult.getMsgTxt());
//            }
            
            PayTransferResult payResult=walletService.updateMerchantWithsDraw(merchantId, groupId, shop.getUserId(), tradeWithdraw.getApplyAmount(), orgOrderNum);
            if(!PayResult.SUCCESS.equals(payResult.getRespCode())){
                throw new ApplicationException(payResult.getRespCode(),payResult.getMsgTxt());
            }
            
            //插入的数据修改填充
            tradeWithdraw.setStatus(BizEnum.WithdrawStatus.WaitingForSettle.getType());
            if (payResult.getOrderId()!=null){
                tradeWithdraw.setWalletOrderId(payResult.getOrderId());
            }
            tradeWithdraw.setTraceNo(orgOrderNum);
            tradeWithdraw.setFee(0);
            tradeWithdraw.setGmtCreate(new Date());
            tradeWithdraw.setGmtModified(new Date());
            tradeWithdraw.setSettleCode(merchantId);
            int status=tradeWithdrawMapper.insert(tradeWithdraw); 
            TradeOffline tradeOffline=addTradeOffline(orgOrderNum, tradeWithdraw.getGroupId(), tradeWithdraw.getApplyAmount(), shop.getId(), shop.getMerchantName(),1);
            tradeOfflineMapper.insertSelective(tradeOffline);
            return status;
        }

       return 1;
    }
    
        //shopOrAgent代理或门店标志：1表示门店，2表示代理
	    public TradeOffline addTradeOffline(String orgOrderNum,Long groupId,Integer tranAmt,Long payerId,String payerName,int shopOrAgent){
	    	TradeOffline tradeOffline=new TradeOffline();
	    	Date date=new Date();
		    tradeOffline.setGmtCreate(date);
		    tradeOffline.setGmtModified(date);
		    tradeOffline.setGroupId(groupId);
		    tradeOffline.setOrderId(Const.PLATFORM_WITHDEAW+UtilFun.createOrderNum());
		    tradeOffline.setPayerId(payerId);//付款者id号
		    tradeOffline.setPayerName(payerName);//付款者姓名
            if(shopOrAgent==1) {
                tradeOffline.setPayerType((byte) CommonEnum.UserType.Store.getType());
            }else if(shopOrAgent==2){
                tradeOffline.setPayerType((byte) CommonEnum.UserType.Agents.getType());
            }
            tradeOffline.setPayType((byte) BizEnum.PaymentType.Wallet.getType());//支付方式 生成订单支付方式未知
		    tradeOffline.setReceiverId(payerId+"");//接收者id        提现付款者接收者暂设置为同一
		    tradeOffline.setReceiverName(payerName);//接收者 此处以核销录入数据
            if(shopOrAgent==1) {
                tradeOffline.setReceiverType((byte) CommonEnum.UserType.Store.getType());
            }else if(shopOrAgent==2){
                tradeOffline.setReceiverType((byte) CommonEnum.UserType.Agents.getType());
            }
		    tradeOffline.setTransactionType((byte)BizEnum.TransactionType.Withdraw.getType());//交易类型
//		    tradeOffline.setSubType((byte)BizEnum.PaymentScene.Online.getType());//支付场景
		    tradeOffline.setOrderAmount(tranAmt); //订单金额
		    tradeOffline.setDiscountAmount(0);//折扣金额
		    tradeOffline.setRealAmount(tranAmt);//实付金额
		    tradeOffline.setTransactionStatus((byte)BizEnum.TransactionStatus.Proccessing.getType());//交易状态
		    tradeOffline.setIsWallet(false);
		    tradeOffline.setGoodType(null);//商品类型(线上用) ？
		    tradeOffline.setMemo("平台申请提现");
		    tradeOffline.setDetail("平台申请提现");
		    tradeOffline.setMerchantNo(null);//商户号(对账用)
		    tradeOffline.setTerminalNo(null);//商户终端号
		    tradeOffline.setPayAccount(null);//支付卡号
		    tradeOffline.setScanOrganization((byte)BizEnum.ScanInNetCompany.fuqianla.getType());//扫码付入网机构
		    tradeOffline.setCrcodeStr(null); 
		    tradeOffline.setOldOrderId(null); 
		    tradeOffline.setDividableAmount(0);//可分润金额
		    tradeOffline.setAttachStatus(BizEnum.ProfitCalculateStatus.NoDeal.getType());
		    tradeOffline.setPayOrderid(orgOrderNum);//钱包充值
		    tradeOffline.setPayBakOrderid(null);
		    tradeOffline.setInNetCompany(null);//入网机构

			return tradeOffline;
	    	
	    }

   
}
